﻿using AutoMapper;
using DFGK.WMS.Common.Web;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.IRepository.IService;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.Models.PDA;
using DFGK_WMS.Repository.Service;
using DFGK_WMS.WebAPI.Tools;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.VisualBasic;
using NetTaste;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using System.Text.RegularExpressions;
using static DFGK_WMS.Model.DTO.ShelvesSinles;

namespace DFGK_WMS.Repository
{
    public class TReceivingBillRepository : BaseRepository<Model.Models.TReceivingBill>, ITReceivingBillRepository
    {
        public IBarCodeRuleRepository BarCodeRuleRepository { get; }
        public ITReceivingOrderDetailRepository TReceivingOrderDetail { get; }
        public IStackingStorageService StackingStorageService { get; }
        public ITLogRepository TLogRepository { get; }

        public TReceivingBillRepository(DFGK_DB context, IMapper mapper, IBarCodeRuleRepository barCodeRuleRepository, ITReceivingOrderDetailRepository tReceivingOrderDetail, IStackingStorageService stackingStorageService, ITLogRepository tLogRepository) : base(context, mapper)
        {
            BarCodeRuleRepository = barCodeRuleRepository;
            TReceivingOrderDetail = tReceivingOrderDetail;
            StackingStorageService = stackingStorageService;
            TLogRepository = tLogRepository;
        }

        /// <summary>
        /// 逻辑分区
        /// </summary>
        /// <returns></returns>
        public List<TDictItem> GetDictItems()
        {
            var list = Context.TDictItems
                .Where(x => x.TypeId == 41);

            if (list == null)
            {
                return null;
            }

            return list.ToList();
        }

        /// <summary>
        /// 添加收货单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddReceivingBill(Model.Models.TReceivingBill m, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    string supname = "";
                    string cusname = "";
                    message = "";
                    //供应商信息
                    if (m.SupplierId != null)
                    {
                        var sobj = Context.TSuppliers.FirstOrDefault(s => s.Id == m.SupplierId);
                        if (sobj != null)
                        {
                            //m.SupplierName = sobj.Name;
                            supname = sobj.Name;
                        }
                        else
                        {
                            message = "供应商不存在或者已被禁用！";
                            tran.Rollback();
                            return false;
                        }
                    }
                    if (m.CustomerId.GetValueOrDefault() > 0)
                    {
                        var cobj = Context.TCustomers.FirstOrDefault(s => s.Id == m.CustomerId);
                        if (cobj != null)
                        {
                            //m.SupplierName = sobj.Name;
                            cusname = cobj.Name;
                        }
                        else
                        {
                            message = "客户不存在或者已被禁用！";
                            tran.Rollback();
                            return false;
                        }
                    }
                    m.SupplierName = supname;
                    m.CustomerName = cusname;
                    m.WarehouseId = 2;
                    m.WarehouseName = "中煤科院仓库";
                    m.WarehouseCode = "A01";
                    //初始化状态
                    m.Status = 0;
                    //默认收货数量
                    m.ReceivedQTY = 0;
                    m.BeginDate = DateTime.Now;
                    m.ShelvesNo = m.BillNo;
                    m.OrderUnit = "PC";
                    m.BaseUnit = "PC";
                    m.CreateDate = DateTime.Now;
                    foreach (var item in m.BillDetailList)
                    {
                        TReceivingBill rebillobj = new TReceivingBill();

                        rebillobj = Mapper.Map<TReceivingBill>(m);
                        rebillobj.OrderId = item.OrderId;
                        rebillobj.NoticeLineNo = item.NoticeLineNo;
                        rebillobj.TotalCheckQty = item.TotalCheckQty;
                        rebillobj.TotalQty = item.Qty;
                        Context.TReceivingBills.Add(rebillobj);
                        Context.SaveChanges();


                        if (item.Qty <= 0)
                        {
                            message = "收货数量不能小于0";
                            tran.Rollback();
                            return false;
                        }
                        if (item.Qty % 1 != 0)
                        {
                            message = "收货数量包含小数";
                            tran.Rollback();
                            return false;
                        }
                        //供应商
                        //item.SupplierId = m.SupplierId;
                        item.SupplierName = supname;
                        //关联单号
                        item.BillNo = rebillobj.BillNo;
                        item.BillId = rebillobj.Id;
                        //初始化状态
                        item.Status = 0;
                        //创建日期
                        item.CreateDate = DateTime.Now;
                        Context.TReceivingBillDetails.Add(item);
                    }
                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    tran.Rollback();
                    return false;
                    throw;
                }
            }
        }

        /// <summary>
        /// PC/PDA收货入库
        /// </summary>
        /// <param name="receivingBillOrderDto"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddPDAReceivingOrderDateil(ReceivingBillOrderDto m, out string message, ref List<TCell> Getcell)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
                try
                {
                    var receivingBills = Context.TReceivingBills.FirstOrDefault(r => r.Id == m.Id);
                    if (receivingBills == null)
                    {
                        message = "收货单不存在";
                        return false;
                    }
                    var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == receivingBills.Id).ToList();

                    foreach (var item in rbd)
                    {
                        if (item.ReceivedQty <= 0)
                        {
                            continue;
                        }
                        receivingBills.ReceivedQTY = receivingBills.ReceivedQTY.GetValueOrDefault() + item.ReceivedQty;
                    }
                    string receordercode = receivingBills.ShelvesNo;

                    #region 西安弃用
                    ////查看收货单已收货数量是否是0 （是的话创建一个入库单编号 不是0查询出入库单编号）
                    //if (receivingBills.ReceivedQTY == 0 || receivingBills.ReceivedQTY is null)
                    //{
                    //    receordercode = BarCodeRuleRepository.GetBarCodeSample(1);
                    //    if (string.IsNullOrEmpty(receordercode) || receordercode.Length == 0)
                    //    {
                    //        //trans.Rollback();
                    //        message = "入库单编码不存在或已被禁用！";
                    //        tran.Rollback();
                    //        return false;
                    //    }
                    //}
                    //else
                    //{
                    //    var rece = Context.TReceivingOrderDetails.AsNoTracking().FirstOrDefault(r => r.ReceivingBillId == receivingBills.Id);
                    //    if (rece is null)
                    //    {
                    //        message = "入库单编码不存在！";
                    //        tran.Rollback();
                    //        return false;
                    //    }
                    //    receordercode = rece.OrderSn;
                    //}
                    #endregion

                    decimal count = 0;//计算数量
                    var rebildatails = Context.TReceivingBillDetails.AsQueryable();
                    var palllist = Context.TPallets.AsQueryable();
                    foreach (var item in m.ReceivingBillOrderDetailDtos)
                    {
                        if (item.ReceivedQty < 0)
                        {
                            message = "收货数量不能小于0";
                            tran.Rollback();
                            return false;
                        }
                        if (item.ReceivedQty % 1 != 0)
                        {
                            message = "收货数量包含小数";
                            tran.Rollback();
                            return false;
                        }
                        var r = rebildatails.FirstOrDefault(x => x.Id == item.ReceivingBillDetailId); //Context.TReceivingBillDetails.Find(item.ReceivingBillDetailId);
                        if (r is null)
                        {
                            message = "收货单明细不存在";
                            tran.Rollback();
                            return false;
                        }
                        else
                        {
                            if (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode) )
                            {
                                message = "托盘为空";
                                return false;
                            }
                            if (r.Qty >= item.ReceivedQty && (r.ReceivedQty + item.ReceivedQty) <= r.Qty)
                            {
                                r.ReceivedQty += item.ReceivedQty;
                                count += item.ReceivedQty;
                                if (r.Price is not null || r.Price >= 0)
                                {
                                    receivingBills.TotalPrice += (decimal)r.Price * item.ReceivedQty;
                                }
                            }
                            else
                            {
                                message = "收货数量不能大于物料数量";
                                tran.Rollback();
                                return false;
                            }
                            Context.TReceivingBillDetails.Update(r);
                            Context.SaveChanges();
                        }
                        var palletbarList = palllist.Where(x => x.PalletBarcode == item.PalletBarcode); //Context.TPallets.Where(x => x.PalletBarcode == item.PalletBarcode);
                        if (palletbarList.Count() <= 0)
                        {
                            message = "未查询到此托盘" + item.PalletBarcode;
                            tran.Rollback();
                            return false;
                        }
                        var palletBarListUpd = palletbarList.First();
                        palletBarListUpd.LoadFactor = item.LoadFactor;
                        Context.TPallets.Update(palletBarListUpd);
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "更新托盘表失败";
                            tran.Rollback();
                            return false;
                        }
                    }
                    var res = Context.TReceivingBillDetails.Where(x => x.BillId == receivingBills.Id).ToList();
                    bool reresult = false;
                    foreach (var item in rbd)
                    {
                        count += item.ReceivedQty;
                    }
                    if (count == receivingBills.TotalQty)
                    {
                        reresult = AddReceivingOrderDeatils(m, receordercode, out message, ref Getcell);
                        if (!reresult)
                        {
                            message = message;
                            tran.Rollback();
                            return false;
                        }
                        receivingBills.Status = 2;
                        receivingBills.EndDate = DateTime.Now;
                        Context.TReceivingBills.Update(receivingBills);
                        Context.SaveChanges();
                    }
                    if (count < receivingBills.TotalQty)
                    {
                        reresult = AddReceivingOrderDeatils(m, receordercode, out message, ref Getcell);
                        if (!reresult)
                        {
                            message = message;
                            tran.Rollback();
                            return false;
                        }
                        receivingBills.Status = 1;
                        Context.TReceivingBills.Update(receivingBills);
                        Context.SaveChanges();
                    }

                    Context.SaveChanges();
                    //提交事务
                    message = "收货成功";
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    TLogRepository.Add(new TLog()
                    {
                        ActionType = 0,
                        CreateDate = DateTime.Now,
                        Description = message,
                        LogType = 1,
                        UserName = m.NowUserRealName
                    });
                    tran.Rollback();
                    return false;
                    throw;
                }
        }

        #region 封装方法收货入库
        /// <summary>
        /// 添加入库单管理
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTReceivingOrderDetail(TReceivingOrderDetail m, out string message)
        {
            message = "";

            //货主信息
            if (m.OwnerId.HasValue)
            {
                //var depobj = Context.TDepartments.AsQueryable();
                //var depowobj = Context.TDepartmentOwners.Where(x => x.OwnerId == m.OwnerId);
                //var owobj = Context.TOwners.Where(x=>x.Status==1);
                //var delist = (from d in depobj
                //              join de in depowobj
                //              on d.Id equals de.DepartmentId
                //              join o in owobj
                //              on de.OwnerId equals o.Id
                //              select d).FirstOrDefault();
                //if (delist != null)
                //{
                //    m.DeptCode = delist.DepartmentCode;
                //    m.DeptName = delist.DepartmentName;
                //    var owerobj = owobj.Where(x => x.Id == m.OwnerId).FirstOrDefault();
                //    if (owerobj != null)
                //    {
                //        m.OwnerName = owerobj.Name;
                //    }
                //}
                //else
                //{
                //    message = "货主不存在，或已被禁用，请先维护";
                //    return false;
                //}
                //var cusobj = Context.TCustomers.AsNoTracking().FirstOrDefault(r => r.Id == m.CustomerId && r.MengNiuStatus == true);
                //if (cusobj != null)
                //{
                //    m.CustomerName = cusobj.Name;
                //}
                //else
                //{
                //    message = "客户不存在，或已被禁用，请先维护";
                //    return false;
                //}

                var owobj = Context.TOwners.Where(x => x.Status == 1);
                var owerobj = owobj.Where(x => x.Id == m.OwnerId).FirstOrDefault();
                if (owerobj != null)
                {
                    if (owerobj != null)
                    {
                        m.OwnerName = owerobj.Name;
                    }
                }
                else
                {
                    message = "货主不存在，或已被禁用，请先维护";
                    return false;
                }
            }
            else
            {
                m.OwnerId = 0;
                m.OwnerName = "";
                m.DeptCode = "";
                m.DeptName = "";
            }

            //库房信息
            var warehouseobj = Context.TWarehouses.Find(m.WarehouseId);
            if (warehouseobj != null && warehouseobj.Status == 1)
            {
                m.WarehouseName = warehouseobj.Name;
                m.WarehouseCode = warehouseobj.Code;
            }
            else
            {
                message = "仓库不存在或仓库已被禁用，请先维护";
                return false;
            }
            //供应商信息
            var supplierobj = Context.TSuppliers.Find(m.SupplierId);
            if (supplierobj != null)
            {
                m.SupplierName = supplierobj.Name;
            }
            //物料信息
            var materialobj = Context.TMaterials.Find(m.MaterialId);
            if (materialobj != null)
            {
                m.MaterialCode = materialobj.Code;
                m.MaterialImg = materialobj.Img;
                m.MaterialName = materialobj.Name;
                m.UnitId = materialobj.UnitId;
                m.UnitName = materialobj.UnitName;
                m.MaterialTypeCode = materialobj.TypeCode;
                m.MaterialTypeName = materialobj.TypeName;
                if (materialobj.ExpirationMonth.HasValue && m.ProductDate.HasValue)
                {
                    m.ExpireDate = m.ProductDate.Value.AddMonths(materialobj.ExpirationMonth.Value);
                }
            }
            //物料批次
            TMaterialKey materialKey = null;
            var materkeyobj = Context.TMaterialKeys.FirstOrDefault(x => x.BatchNo == m.BatchNo && x.MaterialId == m.MaterialId);
            if (materkeyobj != null)
            {
                materialKey = materkeyobj;
            }
            //逻辑分区
            var dicobj = Context.TDictItems.FirstOrDefault(x => x.ItemCode == m.LogicalPartCode);
            if (dicobj != null)
            {
                m.LogicalPartName = dicobj.ItemName;
            }
            #region 无用
            ////订单来源默认手动创建
            //m.SourceType = 2;
            ////质检状态默认为合格
            //m.QualityState = 1;
            //m.ReceivedQty = 0;
            //m.PackagedQty = 0;
            //m.PackQty = 0;

            //采购订单行项目类型
            //m.PurOrderLineType = 0;
            //m.StackedQty = 0;
            #endregion
            //if (materialKey == null)
            //{
            //    TMaterialKey materkeyinsert = new TMaterialKey();
            //    materkeyinsert.BatchNo = m.BatchNo;
            //    materkeyinsert.MaterialId = m.MaterialId;
            //    materkeyinsert.OutFactoryDate = m.OutFactoryDate;
            //    materkeyinsert.OwnerId = m.OwnerId;
            //    materkeyinsert.OwnerName = m.OwnerName;
            //    materkeyinsert.ProduceFactory = m.ProduceFactory;
            //    materkeyinsert.ProductDate = m.ProductDate;
            //    materkeyinsert.Qadate = m.Qadate;
            //    materkeyinsert.SupplierName = m.SupplierName;
            //    materkeyinsert.SupplierId = m.SupplierId;
            //    materkeyinsert.ExpireDate = m.ExpireDate;
            //    materkeyinsert.CreateDate = DateTime.Now;
            //    materkeyinsert.MaterialCode = m.MaterialCode;
            //    materkeyinsert.MaterialName = m.MaterialName;
            //    materkeyinsert.QualityState = m.QualityState;
            //    materkeyinsert.DeptCode = m.DeptCode;
            //    materkeyinsert.DeptName = m.DeptName;
            //    materkeyinsert.Mblnr = m.Mblnr;
            //    materkeyinsert.Mjahr = m.Mjahr;
            //    materkeyinsert.Zeile = m.Zeile;
            //    materkeyinsert.ContractNo = m.ContractNo;
            //    materkeyinsert.PurOrderNo = m.PurOrderNo;
            //    materkeyinsert.PurOrderLineNo = m.PurOrderLineNo;
            //    materkeyinsert.PurOrderLineType = m.PurOrderLineType;
            //    materkeyinsert.ProOrderNo = m.ProOrderNo;
            //    materkeyinsert.OutOrderNo = m.OutOrderNo;
            //    Context.TMaterialKeys.Add(materkeyinsert);
            //    int result = Context.SaveChanges();
            //    if (result == 0)
            //    {
            //        message = "保存失败！";

            //        return false;
            //    }
            //    m.MaterialKeyId = materkeyinsert.Id;
            //}
            if (materialKey != null)
            {
                m.MaterialKeyId = materialKey.Id;
                //var materkey = Context.TMaterialKeys.Find(m.MaterialKeyId);
                //if (materkey != null)
                //{
                //    materkey.BatchNo = m.BatchNo;
                //    materkey.OutFactoryDate = m.OutFactoryDate;
                //    materkey.OwnerId = m.OwnerId;
                //    materkey.OwnerName = m.OwnerName;
                //    materkey.ProduceFactory = m.ProduceFactory;
                //    materkey.ProductDate = m.ProductDate;
                //    materkey.Qadate = m.Qadate;
                //    materkey.SupplierId = m.SupplierId;
                //    materkey.SupplierName = m.SupplierName;
                //    materkey.ExpireDate = m.ExpireDate;
                //    materkey.MaterialCode = m.MaterialCode;
                //    materkey.MaterialName = m.MaterialName;
                //    materkey.QualityState = m.QualityState;
                //    materkey.DeptCode = m.DeptCode;
                //    materkey.DeptName = m.DeptName;
                //    materkey.Mblnr = m.Mblnr;
                //    materkey.Mjahr = m.Mjahr;
                //    materkey.Zeile = m.Zeile;
                //    materkey.ContractNo = m.ContractNo;
                //    materkey.ProOrderNo = m.ProOrderNo;
                //    materkey.PurOrderLineNo = m.PurOrderLineNo;
                //    materkey.PurOrderLineType = m.PurOrderLineType;
                //    materkey.ProOrderNo = m.ProOrderNo;
                //    materkey.OutOrderNo = m.OutOrderNo;
                //    Context.TMaterialKeys.Update(materkey);
                //}
                //int result = Context.SaveChanges();
                //if (result <= 0)
                //{
                //    message = "保存失败！";

                //    return false;
                //}
            }
            Context.TReceivingOrderDetails.Add(m);
            int resultt = Context.SaveChanges();           
            if (resultt > 0)
                return true;
            return false;
        }
        #endregion

        /// <summary>
        /// 强制完成
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool ReceivingBillComplete(int id)
        {
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    var res = Context.TReceivingBills.FirstOrDefault(b => b.Id == id);
                    res.Status = 2;
                    res.EndDate = DateTime.Now;
                    Context.TReceivingBills.Update(res);
                    Context.SaveChanges();

                    var receivingBillDetails = Context.TReceivingBillDetails.Where(r => r.BillId == id).ToList();
                    foreach (var item in receivingBillDetails)
                    {
                        item.Status = 1;
                        Context.TReceivingBillDetails.Update(item);
                        Context.SaveChanges();
                    }
                    Context.SaveChanges();
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 删除收货单
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelReceivingBill(int rid, out string message)
        {
            try
            {
                message = "";
                var robj = Context.TReceivingBills.Find(rid);
                if (robj != null)
                {
                    if (robj.Status == 1 || robj.Status == 2 || robj.Status==3)
                    {
                        message = "已完成的单据不能再删除";
                        return false;
                    }
                    Context.TReceivingBills.Remove(robj);
                    var rodobj = Context.TReceivingBillDetails.FirstOrDefault(x => x.BillId == robj.Id);
                    if (rodobj != null)
                        Context.TReceivingBillDetails.Remove(rodobj);
                    Context.SaveChanges();
                    message = "删除成功!";
                    return true;
                }
                message = "删除失败!";
                return false;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return false;
                throw;
            }

        }

        /// <summary>
        /// 收获管理显示
        /// </summary>
        /// <param name="supplierId"></param>
        /// <param name="status"></param>
        /// <param name="warehouseId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Model.Models.TReceivingBill> GetReceivingBillList(string key, int pageIndex, int pageSize, out int totalCount)
        {
            var rlist = Context.TReceivingBills.AsNoTracking().Where(x => x.Status < 2);
            var rdlist = Context.TReceivingBillDetails.AsNoTracking();

            //if (!string.IsNullOrEmpty(key))
            //{
            //    rlist = rlist.Where(x => x.ShelvesNo.Contains(key));
            //}
            //if (!rlist.Any())
            //    rlist = Context.TReceivingBills.AsNoTracking().Where(x => x.Status < 2);
            List<Model.Models.TReceivingBill> rrlist = new List<TReceivingBill>();
            foreach (var item in rlist)
            {
                var rbdlist = rdlist.AsNoTracking().Where(x => x.BillId == item.Id);
                foreach (var item2 in rbdlist)
                {
                    if (item2.ReceivedQty <= 0)
                    {
                        item.Ngreason = item2.MaterialName;
                        item.Receiver = item2.MaterialCode;
                        rrlist.Add(item);
                        continue;
                    }
                    item.Ngreason = item2.MaterialName;
                    item.Receiver = item2.MaterialCode;
                    item.ReceivedQTY = item.ReceivedQTY.GetValueOrDefault() + item2.ReceivedQty;
                    rrlist.Add(item);
                }
            }
            if (!string.IsNullOrEmpty(key) && rrlist.Count>0)
            {
                rrlist = rrlist.Where(x => x.Receiver.Contains(key)).ToList();
            }
            totalCount = rrlist.Count();
            rrlist = rrlist.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return rrlist;
        }

        /// <summary>
        /// 根据物料分类id返回物料
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TMaterial> GetRidById(int mid)
        {
            var list = Context.TMaterials.Where(x => x.MaterialCategoryId == mid);
            return list.ToList();
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public Model.Models.TReceivingBill GetTReceivingBillById(int rid)
        {
            var robj = Context.TReceivingBills.Find(rid);

            if (robj != null)
            {
                var roobj = Context.TReceivingBillDetails.FirstOrDefault(x => x.BillId == robj.Id);
                if (roobj != null)
                {
                    roobj.OrderId = robj.OrderId;
                    roobj.NoticeLineNo = robj.NoticeLineNo;
                    roobj.TotalCheckQty = robj.TotalCheckQty;
                    robj.BillDetailList = new List<TReceivingBillDetail>
                    {
                        roobj
                    };
                }
                return robj;
            }
            return null;
        }

        /// <summary>
        /// 修改收货单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UpdReceivingBill(Model.Models.TReceivingBill m, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    string supname = "";
                    string cusname = "";
                    var IsStatus = Context.TReceivingBills.FirstOrDefault(r => r.Id == m.Id && r.Status != 0);
                    if (IsStatus is not null || IsStatus != null)
                    {
                        message = "收货单不能再编辑,收货单号：" + IsStatus.BillNo;
                        return false;
                    }
                    message = "";
                    //供应商信息
                    if (m.SupplierId != null)
                    {
                        var sobj = Context.TSuppliers.FirstOrDefault(s => s.Id == m.SupplierId);
                        if (sobj != null)
                        {
                            //m.SupplierName = sobj.Name;
                            supname = sobj.Name;
                        }
                        else
                        {
                            message = "供应商不存在或者已被禁用！";
                            tran.Rollback();
                            return false;
                        }
                    }
                    if (m.CustomerId.GetValueOrDefault() > 0)
                    {
                        var cobj = Context.TCustomers.FirstOrDefault(s => s.Id == m.CustomerId);
                        if (cobj != null)
                        {
                            //m.SupplierName = sobj.Name;
                            cusname = cobj.Name;
                        }
                        else
                        {
                            message = "客户不存在或者已被禁用！";
                            tran.Rollback();
                            return false;
                        }
                    }
                    m.SupplierName = supname;
                    m.CustomerName = cusname;
                    m.WarehouseId = 2;
                    m.WarehouseName = "中煤科院仓库";
                    m.WarehouseCode = "A01";

                    foreach (var item in m.BillDetailList)
                    {
                        m.OrderId = item.OrderId;
                        m.NoticeLineNo = item.NoticeLineNo;
                        m.TotalCheckQty = item.TotalCheckQty;
                        m.TotalQty = item.Qty;
                        Context.TReceivingBills.Update(m);
                        Context.SaveChanges();
                        if (item.Qty <= 0)
                        {
                            message = "数量不能小于0";
                            tran.Rollback();
                            return false;
                        }
                        if (item.Qty % 1 != 0)
                        {
                            message = "数量包含小数";
                            tran.Rollback();
                            return false;
                        }

                        Context.TReceivingBillDetails.Update(item);
                    }


                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdReceivingBillStatus(int rid)
        {
            var robj = Context.TReceivingBills.Find(rid);
            if (robj != null)
            {
                robj.Status = 2;
                Context.TReceivingBills.Update(robj);
                Context.SaveChanges();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 添加入库单的方法仅本类使用
        /// </summary>
        /// <param name="m"></param>
        /// <param name="receordercode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool AddReceivingOrderDeatils(ReceivingBillOrderDto m, string receordercode, out string message, ref List<TCell> Getcell)
        {
            message = "";
            bool reresult = false;
            var receinvingd = Context.TReceivingBillDetails.AsNoTracking();
            foreach (var item in m.ReceivingBillOrderDetailDtos)
            {
                string? entryType = receinvingd.FirstOrDefault(x => x.Id == item.ReceivingBillDetailId)?.BillLineNo;
                //空托盘
                string? artic = receinvingd.FirstOrDefault(x => x.Id == item.ReceivingBillDetailId)?.Articlebarcode;
                if (entryType==null)
                {
                    entryType = "";
                }
                if (artic == null)
                {
                    artic = "";
                }
                TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                if (item.ReceivedQty == 0 || (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode) || string.IsNullOrEmpty(item.PalletBarcode)))
                {
                    if (!reresult)
                    {
                        message = "收货数量或托盘或批次有误";
                        reresult = false;
                    }
                    continue;
                }

                message = "";
                receivingOrder.OrderSn = receordercode;
                //本地入库
                receivingOrder.BillType = 1;
                receivingOrder.WarehouseId = m.Wid;
                receivingOrder.SupplierId = m.Suppid;
                receivingOrder.MaterialId = item.MaterialId;
                receivingOrder.OwnerId = item.OwerId;
                receivingOrder.BatchNo = item.MaterialBatchNo;
                receivingOrder.SmallBatchNo = item.SmallBatchNo;
                receivingOrder.CustomerId = m.CustomerId;
                //订单来源默认手动创建
                receivingOrder.SourceType = 2;
                //质检状态默认为合格
                receivingOrder.QualityState = 1;
                //质量状态
                receivingOrder.Status = 3;
                receivingOrder.ReceivedQty = 0;
                receivingOrder.PackagedQty = 0;
                receivingOrder.PackQty = 0;
                receivingOrder.BatchNoExplain = item.BatchNoExplain;
                receivingOrder.OutFactoryDate = item.OutFactoryDate;
                receivingOrder.ProduceFactory = item.ProduceFactory;
                receivingOrder.ProductDate = item.ProductDate;
                receivingOrder.ExpireDate = item.ExpireDate;
                receivingOrder.Remark = item.Remark;
                receivingOrder.Qty = item.ReceivedQty;
                receivingOrder.PalletBarcode = item.PalletBarcode;
                //判断是否采购订单
                receivingOrder.Erpcode = entryType;
                #region 审计字段
                receivingOrder.CreateUserId = m.NowUserId;
                receivingOrder.CreateUserName = m.NowUserRealName;
                receivingOrder.CreateDate = DateTime.Now;
                receivingOrder.AuditUserId = m.NowUserId;
                receivingOrder.AuditUserName = m.NowUserRealName;
                receivingOrder.AuditDate = DateTime.Now;
                receivingOrder.SubmitUserId = m.NowUserId;
                receivingOrder.SubmitUserName = m.NowUserRealName;
                receivingOrder.SubmitDate = DateTime.Now;
                receivingOrder.ReceivingBillId = m.Id;
                //判断是否是砖头
                receivingOrder.RefInVoucherId = m.DictReceivingId;
                if (artic != null && artic.Length > 0)
                    receivingOrder.Remark = artic;
                #endregion
                    //采购订单行项目类型
                receivingOrder.PurOrderLineType = 0;
                receivingOrder.StackedQty = 0;
                reresult = AddTReceivingOrderDetail(receivingOrder, out message);
                if (reresult == false)
                {
                    message = "添加入库单失败" + message;
                    return false;
                }
                var receiving = Context.TReceivingOrderDetails.First(r => r.Id == receivingOrder.Id);
                PalletTallyInputModel palletTallyInputModel = new PalletTallyInputModel();
                palletTallyInputModel.PalletBarcode = item.PalletBarcode;
                palletTallyInputModel.TotalNum = item.ReceivedQty;
                palletTallyInputModel.OrderDetailId = receiving.Id;
                palletTallyInputModel.WarehouseId = receiving.WarehouseId;
                palletTallyInputModel.LogicPartCode = receiving.LogicalPartCode;
                palletTallyInputModel.PalletPackage.MaterialCode = receiving.MaterialCode;
                reresult = StackingStorageService.BuildCreateStackingStorageEF(out message, palletTallyInputModel, ref Getcell);
                if (!reresult)
                {
                    if (message is null || message == "")
                    {
                        message = "保存组箱数据失败";
                    }
                    else
                    {
                        message = message;
                    }
                    return false;
                }
            }
            return reresult;
        }

        /// <summary>
        /// 入库任务下传
        /// </summary>
        /// <param name="sList"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool ReceivingTaskDownload(List<ShelvesSinles> sList, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    message = "";
                    var existingOrderIds = Context.TReceivingBills.AsNoTracking().Where(x => sList.Select(s => s.Id).Distinct().Contains(x.OrderId)).Select(x => x.OrderId).ToList();
                    var materobj1 = Context.TMaterial.AsNoTracking();
                    foreach (var shelves in sList)
                    {
                        if (existingOrderIds.Contains(shelves.Id))
                        {
                            message += shelves.Id + "存在重复";
                            continue;
                        }                  
                        var r = new TReceivingBill();
                        r.OrderId = shelves.Id;
                        r.ShelvesNo = shelves.ShelvesNo;
                        r.BaseUnit = shelves.BaseUnit;
                        r.BillNo = shelves.ShelvesNo;
                        r.SupplierName = shelves.SupplierName;
                        r.Status = 0;
                        r.CreateDate = Convert.ToDateTime(shelves.CreateTime);
                        r.StoLocation = shelves.StockLocation;
                        //总数量
                        r.TotalQty = shelves.ShelvesQuantity;
                        r.TotalCheckQty = shelves.BaseQuantity;
                        r.CreateUserName = shelves.Founder;
                        r.OrderUnit = shelves.OrderUnit;
                        r.NoticeNo = shelves.NoticeNo;
                        r.NoticeLineNo = shelves.NoticeLineNo;
                        r.Workers = shelves.Workers;
                        r.StorageArea = shelves.StorageArea;
                        r.BinNo = shelves.BinNo;
                        r.RefSn = shelves.SapOrderNo;
                        r.DictReceiving = shelves.SapOrderLineNo;
                        r.WarehouseId = 2;
                        r.WarehouseName = "中煤科院仓库";
                        r.WarehouseCode = "A01";
                        Context.TReceivingBills.Add(r);
                        Context.SaveChanges();
                        var receivingBillDetail = new TReceivingBillDetail();
                        receivingBillDetail.BillId = r.Id;
                        receivingBillDetail.BillNo = r.BillNo;
                        //receivingBillDetail.BillLineNo = shelves.ShelvesNo;
                        receivingBillDetail.MaterialCode = shelves.MaterialNo;
                        receivingBillDetail.MaterialName = shelves.MaterialDesc;
                        var materobj = materobj1.AsNoTracking().FirstOrDefault(x => x.Code == shelves.MaterialNo);
                        if (materobj != null)
                        {
                            receivingBillDetail.MaterialId = materobj.Id;
                        }
                        else
                        {
                            TMaterial material = new TMaterial();
                            material.Code = shelves.MaterialNo;
                            material.Name = shelves.MaterialDesc;
                            material.CreateDate = DateTime.Now;
                            material.UnitName = shelves.BaseUnit;
                            material.GrossWeightUnitName = "KG";
                            material.NetWeightUnitName = "KG";
                            Context.TMaterial.Add(material);
                            Context.SaveChanges();
                            receivingBillDetail.MaterialId = material.Id;
                        }
                        if (shelves.BatchSerial != null)
                        {
                            if (shelves.BatchSerial.Any())
                            {
                                foreach (var item in shelves.BatchSerial)
                                {
                                    receivingBillDetail.MaterialSerialize += item.MaterialSerialize+",";
                                }
                                receivingBillDetail.MaterialSerialize = receivingBillDetail.MaterialSerialize.TrimEnd(',');
                            }
                        }
                        receivingBillDetail.Qty = shelves.ShelvesQuantity;
                        receivingBillDetail.ReceivedQty = 0;
                        receivingBillDetail.Status = 0;
                        receivingBillDetail.CreateDate = Convert.ToDateTime(shelves.CreateTime);
                        receivingBillDetail.SupplierName = shelves.SupplierName;
                        receivingBillDetail.BatchNo = shelves.BatchNo;
                        receivingBillDetail.ProduceFactory = shelves.Factory;
                        receivingBillDetail.SerialnoParam = shelves.SerialnoParam;
                        receivingBillDetail.BillLineNo = shelves.EntryType;
                        Context.TReceivingBillDetails.Add(receivingBillDetail);
                        existingOrderIds.Add(shelves.Id);
                    }

                    //提交保存
                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    tran.Rollback();
                    return false;
                    throw;
                }
            }
        }

        /// <summary>
        /// 获取提交入库的数据
        /// </summary>
        /// <returns></returns>
        public List<ShelvesSinles> GetSubmitOutList()
        {
            List<ShelvesSinles> slist = new List<ShelvesSinles>();
            var reolist = Context.TReceivingOrderDetails.AsNoTracking().Where(x => x.Status == 4 && x.OrderSn.Contains("SJ"));
            var rlist = Context.TReceivingBills.Where(x => x.Status == 2 && x.OrderId.Length > 0 && x.BillNo.Contains("SJ")).AsNoTracking().OrderBy(r => r.CreateDate);
            var list = (from r in reolist
                        join ro in rlist
                        on r.ReceivingBillId equals ro.Id
                        select ro);
            if (rlist.Any())
            {

                foreach (var item in list)
                {
                    ShelvesSinles sobj = new ShelvesSinles();
                    sobj.Id = item.OrderId;
                    sobj.ShelvesNo = item.ShelvesNo;
                    sobj.BaseUnit = item.BaseUnit;
                    sobj.SupplierName = item.SupplierName;
                    sobj.CreateTime = item.CreateDate.ToString();
                    sobj.StockLocation = item.StoLocation;
                    sobj.BaseQuantity = item.TotalCheckQty == null ? 0 : (decimal)item.TotalCheckQty;
                    sobj.Founder = item.CreateUserName;
                    sobj.OrderUnit = item.OrderUnit;
                    sobj.NoticeNo = item.NoticeNo;
                    sobj.SapOrderNo = item.RefSn;
                    sobj.SapOrderLineNo = item.DictReceiving;
                    sobj.NoticeLineNo = item.NoticeLineNo;
                    sobj.Workers = item.Workers;
                    sobj.StorageArea = item.StorageArea;
                    var locode = reolist.AsNoTracking().FirstOrDefault(x => x.ReceivingBillId == item.Id);
                    sobj.BinNo = locode.LocationCode;
                    var revbilldelist = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == item.Id);
                    if (revbilldelist.Any())
                    {
                        foreach (var item2 in revbilldelist)
                        {
                            
                            sobj.MaterialNo = item2.MaterialCode;
                            sobj.MaterialDesc = item2.MaterialName;
                            sobj.ShelvesQuantity = item2.Qty;
                            sobj.CreateTime = item2.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
                            sobj.SupplierName = item2.SupplierName;
                            sobj.BatchNo = item2.BatchNo;
                            sobj.Factory = item2.ProduceFactory;
                            sobj.SerialnoParam = item2.SerialnoParam;
                            sobj.EntryType = item2.BillLineNo;
                            if(!string.IsNullOrEmpty(item2.MaterialSerialize))
                            {
                                item2.MaterialSerialize = item2.MaterialSerialize.TrimEnd(',');
                                foreach (var item3 in item2.MaterialSerialize.Split(','))
                                {
                                    BatchSerials bserobj = new BatchSerials();
                                    bserobj.MaterialSerialize = item3;
                                    sobj.BatchSerial.Add(bserobj);
                                }
                            }
                            else
                            {
                                BatchSerials bserobj = new BatchSerials();
                                bserobj.MaterialSerialize = item2.MaterialSerialize;
                                sobj.BatchSerial.Add(bserobj);
                            }
                           
                        }
                    }

                    slist.Add(sobj);
                    #region 暂时弃用
                    //var rbds = Context.TReceivingBillDetails.Where(x => x.BillNo == reces.BillNo).AsNoTracking().ToList();
                    //foreach (var item2 in rbds)
                    //{
                    //    List<BatchSerials> bList = new List<BatchSerials>();
                    //    foreach (var b in bList)
                    //    {
                    //        b.Id = item2.MaterialSerializeId;
                    //        b.MaterialSerialize = item2.MaterialSerialize;
                    //        b.BatchNo = item2.MaterialSerializeBatchNo;
                    //        bList.Add(b);
                    //    }
                    //    ShelvesSinles data = new ShelvesSinles()
                    //    {
                    //        Id = reces.BillNo,
                    //        StockLocation = reces.StoLocation,
                    //        SupplierName = reces.SupplierName,
                    //        CreateTime = Convert.ToString(reces.CreateDate),
                    //        BaseQuantity = Convert.ToDecimal(reces.TotalQty),
                    //        Founder = reces.CreateUserName,
                    //        OrderUnit = reces.OrderUnit,
                    //        NoticeNo = reces.NoticeNo,
                    //        NoticeLineNo = reces.NoticeLineNo,
                    //        Workers = reces.Workers,
                    //        ShelvesNo = item2.BillLineNo,
                    //        MaterialNo = item2.MaterialCode,
                    //        MaterialDesc = item2.MaterialName,
                    //        BatchNo = item2.BatchNo,
                    //        Factory = item2.ProduceFactory,
                    //        SerialnoParam = item2.SerialnoParam,
                    //        BatchSerial = bList,

                    //        //仓位
                    //        BinNo = item.LocationCode,
                    //        StorageArea = item.StorageArea,
                    //        ShelvesQuantity = item2.Qty,
                    //    };
                    //    slist.Add(data);
                    //}
                    #endregion
                }
            }


            return slist;
        }

        /// <summary>
        /// 回传成功修改状态
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdBackReceivingState(List<string> ridlist)
        {
            foreach (var rid2 in ridlist)
            {
                var robj = Context.TReceivingBills.AsNoTracking().FirstOrDefault(x => x.OrderId == rid2);
                if (robj != null)
                {
                    robj.Status = 3;
                    Context.TReceivingBills.Update(robj);
                }
            }
            Context.SaveChanges();
            return true;
        }

        /// <summary>
        /// PC收货管理显示
        /// </summary>
        /// <param name="shelvesNo"></param>
        /// <param name="material"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<ShelvesSinlesList> GetSheliveslist(string shelvesNo, string material, int? status, int pageIndex, int pageSize, out int totalCount)
        {
            var slist = Context.TReceivingBills.AsNoTracking();
            var solist = Context.TReceivingBillDetails.AsNoTracking();
            if (!string.IsNullOrEmpty(shelvesNo))
            {
                slist = slist.Where(x => x.ShelvesNo.Contains(shelvesNo));
            }
            if (status.HasValue && status >= 0)
            {
                slist = slist.Where(x => x.Status == status);
            }
            if (!string.IsNullOrEmpty(material))
            {
                solist = solist.Where(x => x.MaterialName.Contains(material));
            }
            List<ShelvesSinlesList> shelist = new List<ShelvesSinlesList>();
            if (!slist.Any())
            {
                totalCount = 0;
                return shelist;
            }
            foreach (var item in slist)
            {
                ShelvesSinlesList sobj = new ShelvesSinlesList();
                sobj.RId = item.Id;
                sobj.Id = item.OrderId;
                sobj.ShelvesNo = item.ShelvesNo;
                sobj.BaseUnit = item.BaseUnit;
                sobj.SupplierName = item.SupplierName;
                sobj.CreateTime = item.CreateDate.ToString();
                sobj.StockLocation = item.StoLocation;
                sobj.BaseQuantity = item.TotalQty == null ? 0 : (decimal)item.TotalQty;
                sobj.Founder = item.CreateUserName;
                sobj.OrderUnit = item.OrderUnit;
                sobj.NoticeNo = item.NoticeNo;
                sobj.NoticeLineNo = item.NoticeLineNo;
                sobj.Workers = item.Workers;
                sobj.StorageArea = item.StorageArea;
                sobj.BinNo = item.BinNo;
                var rebillist = solist.AsNoTracking().Where(x => x.BillId == item.Id);
                if (rebillist.Any())
                {
                    foreach (var item2 in rebillist)
                    {
                        sobj.MaterialNo = item2.MaterialCode;
                        sobj.MaterialDesc = item2.MaterialName;
                        sobj.ShelvesQuantity = item2.ReceivedQty;
                        sobj.CreateTime = item2.CreateDate.ToString();
                        sobj.SupplierName = item2.SupplierName;
                        sobj.BatchNo = item2.BatchNo;
                        sobj.Factory = item2.ProduceFactory;
                        sobj.SerialnoParam = item2.SerialnoParam;
                        shelist.Add(sobj);
                    }
                }
            }

            totalCount = shelist.Count;
            shelist = shelist.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return shelist;
        }

        /// <summary>
        /// 根据托盘条码带出满载率
        /// </summary>
        /// <param name="pallBarcode"></param>
        /// <returns></returns>
        public int? GetLoadFactorByPallBarcode(string pallBarcode)
        {
            var LoadFactorList = Context.TPallets.Where(x => x.PalletBarcode == pallBarcode);
            if (LoadFactorList.Count() == 0)
            {
                return 0;
            }
            return LoadFactorList.First().LoadFactor == null ? 0 : LoadFactorList.First().LoadFactor;
        }
    }
}
